<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="角色：">
        <el-checkbox-group
          v-for="(item, i) in roleList"
          :key="i"
          v-model="selectRole"
        >
          <el-checkbox :label="item.id">
            {{ item.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { addAdminUserRole, getUserAdminRole } from '@/api/userManagement'
  import { getAllAdminRole } from '@/api/roleManagement'
  import { Register, updateUserInfo } from '@/api/user'

  export default {
    name: 'SetRoleEdit',
    data() {
      return {
        roleList: [],
        selectRole: [],
        form: {},
        rules: {},
        title: '',
        dialogFormVisible: false,
      }
    },
    created() {
      this.getRole()
    },
    methods: {
      async getRole() {
        const { data } = await getAllAdminRole()
        if (data.status == 0) {
          this.roleList = data.body
        } else {
          this.$baseMessage(data.message, 'error')
        }
      },
      async getSelectedRole(id) {
        const { data } = await getUserAdminRole(id)
        if (data.status === 0) {
          let _list = data.body.map((item) => {
            return item.id
          })
          this.selectRole = _list
        } else {
          this.$baseMessage(data.message, 'error')
        }
      },
      showEdit(row) {
        if (!row) {
          this.title = '配置角色'
        } else {
          this.title = '编辑角色'
          this.form = Object.assign({}, row)
        }
        this.getSelectedRole(row.userId)

        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            if (this.selectRole.length === 0) {
              this.$baseMessage('请选择角色！', 'warning')
              return
            }
            let _push = {}
            _push.adminUserId = this.form.userId
            _push.roleIds = this.selectRole
            const { data } = await addAdminUserRole(_push)
            if (data.status === 0) {
              this.$baseMessage(data.message, 'success')
              this.close()
            } else {
              this.$baseMessage(data.message, 'error')
            }
          } else {
            return false
          }
        })
      },
    },
  }
</script>
